package com.dynamic.mybatis.core.parser;

import com.dynamic.mybatis.core.exceptions.MyBatisMappedStatementNotPresentException;
import com.dynamic.mybatis.core.utils.StringUtils;

import java.util.Objects;
import java.util.UUID;

public class NamespaceHelper {
    public final static String DEFAULT_TENANT = "default";
    public final static String DEFAULT_NAMESPACE = "default";

    public static String getDynamicMappedStatementId(String tenantCode,String namespace, String shortId) {
        namespace = getNamespace(tenantCode,namespace);
        shortId = Objects.toString(shortId, "");
        if (shortId.startsWith(namespace)) {
            return shortId;
        }
        return namespace.endsWith(".") ? namespace + shortId : namespace + "." + shortId;
    }

    public static String getRandomNamespace() {
        return UUID.randomUUID().toString().replaceAll("-", "") + "." + UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String getNamespace(String tenantCode,String namespace) {
        return StringUtils.toString(tenantCode,DEFAULT_TENANT)+"."+StringUtils.toString(namespace,DEFAULT_NAMESPACE);
    }

    public static String getIdentity(String tenantCode,String namespace, String id) {
        namespace = getNamespace(tenantCode,namespace);
        return namespace.endsWith(".") ?  namespace + id : namespace + "." + id;
    }

    public static String getIdentity(String tenantCode, String id) {
        return tenantCode.endsWith(".") ? StringUtils.toString(tenantCode,DEFAULT_TENANT) + id : tenantCode + "." + id;
    }
}
